package cn.xing.modules.app.service.impl;

import cn.hutool.core.date.DateTime;
import cn.xing.common.exception.RRException;
import cn.xing.common.utils.PageUtils;
import cn.xing.common.utils.Query;
import cn.xing.modules.app.dao.UserReminderDao;
import cn.xing.modules.app.entity.OrderEntity;
import cn.xing.modules.app.entity.UserReminderEntity;
import cn.xing.modules.app.remindvo.OrderChangeVo;
import cn.xing.modules.app.service.OrderService;
import cn.xing.modules.app.service.UserReminderService;
import cn.xing.modules.sys.entity.AfterSaleEntity;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;


@Service("userReminderService")
public class UserReminderServiceImpl extends ServiceImpl<UserReminderDao, UserReminderEntity> implements UserReminderService {
    @Autowired
    private OrderService orderService;
    private final String MSG_TEMPLATE = "您的订单[%s]，商家已[%s]";
    private final String AFTER_SALE_MSG_TEMPLATE = "您的售后[%s]，商家已[%s]";

    private void onOrderStatusChange(OrderEntity orderEntity, int type, String orderStatusChinese) {
        UserReminderEntity userReminderEntity = new UserReminderEntity();
        userReminderEntity.setUserId(orderEntity.getUserId());
        userReminderEntity.setReaded(0);
        userReminderEntity.setType(type);

        String orderSn = orderEntity.getOrderSn();
        String content = buildMsg(orderSn, orderStatusChinese);
        userReminderEntity.setContent(content);

        OrderChangeVo orderChangeVo = new OrderChangeVo(orderSn);
        userReminderEntity.setParams(JSON.toJSONString(orderChangeVo));

        this.baseMapper.insert(userReminderEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void onAfterSaleStatusChange(AfterSaleEntity afterSaleEntity,String afterSaleStatusChinese) {
        String orderSn = afterSaleEntity.getOrderSn();
        OrderEntity orderEntity = orderService.getByOrderSn(orderSn);
        if (orderEntity == null) {
            throw new RRException("订单不存在");
        }
        UserReminderEntity userReminderEntity = new UserReminderEntity();

        userReminderEntity.setUserId(orderEntity.getUserId());
        userReminderEntity.setReaded(0);
        userReminderEntity.setType(1);


        String content = String.format(AFTER_SALE_MSG_TEMPLATE, orderSn,afterSaleStatusChinese );
        userReminderEntity.setContent(content);

        OrderChangeVo orderChangeVo = new OrderChangeVo(orderSn);
        userReminderEntity.setParams(JSON.toJSONString(orderChangeVo));

        this.baseMapper.insert(userReminderEntity);
    }

    @Override
    public void markAllReaded(Long userId) {
        this.baseMapper.markAllReaded(userId, new Date());
    }

    @Override
    public UserReminderEntity markReaded(Long id) {
        UserReminderEntity byId = getById(id);
        if (byId == null) {
            throw new RRException("该提醒不存在");
        }
        // 标记已读
        byId.setReaded(1);
        byId.setReadTime(new DateTime());

        updateById(byId);
        return byId;
    }

    @Override
    public void onAfterSaleConfirm(AfterSaleEntity afterSaleEntity) {
        onAfterSaleStatusChange(afterSaleEntity,"商家接受退款");
    }

    @Override
    public void onAfterSaleRefuse(AfterSaleEntity afterSaleEntity) {
        onAfterSaleStatusChange(afterSaleEntity,"商家拒绝退款");
    }

    @Override
    public void onOrderCancel(OrderEntity orderEntity) {
        onOrderStatusChange(orderEntity, 0, "取消");
    }


    @Override
    public void onOrderRefunded(OrderEntity orderEntity) {
        onOrderStatusChange(orderEntity, 0, "退款");
    }

    @Override
    public void onOrderSendOut(OrderEntity orderEntity) {
        onOrderStatusChange(orderEntity, 0, "送出");
    }

    @Override
    public void onOrderSended(OrderEntity orderEntity) {
        onOrderStatusChange(orderEntity, 0, "送达");
    }

    @Override
    public void onOrderTaken(OrderEntity orderEntity) {
        onOrderStatusChange(orderEntity, 0, "接单");

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long userId) {
        // 默认只查未读的
        int readed = Integer.parseInt( params.getOrDefault("readed", "0").toString());

        IPage<UserReminderEntity> page = this.page(
                new Query<UserReminderEntity>().getPage(params),
                new QueryWrapper<UserReminderEntity>()
                        .eq("readed", readed)
                        // 查询自己的
                        .eq("user_id", userId)
                        .orderByDesc("create_time")

        );

        return new PageUtils(page);
    }


    private String buildMsg(String orderSn, String orderStatusChinese) {
        return String.format(MSG_TEMPLATE, orderService.buildOrderSubject(orderSn), orderStatusChinese);
    }
}